pcall(require, "luarocks.loader")


local gears         = require("gears")
local awful         = require("awful")
require("awful.autofocus")
-- Widget and layout library
local wibox         = require("wibox")
-- Theme handling library
local beautiful     = require("beautiful")
-- Notification library
local naughty       = require("naughty")
local freedesktop   = require("freedesktop")
local menubar       = require("menubar")
local hotkeys_popup = require("awful.hotkeys_popup")
local brightness = require("mywidgets.brightness")
local volume = require("mywidgets.volume")

----------------------------------------------------------------------------------- custom functions ------------------------------------------------------------------------------------------------------------
function toogle_to_tag(i)
        local screen = awful.screen.focused()
        local tag = screen.tags[i]
        if tag then
           tag:view_only()
        end
end

require("awful.hotkeys_popup.keys")

-- {{{ Error handling
if awesome.startup_errors then
	naughty.notify({ preset = naughty.config.presets.critical,
		title               = "Oops, there were errors during startup!",
		text                = awesome.startup_errors })
end

-- Handle runtime errors after startup
do
	local in_error              = false
	awesome.connect_signal("debug::error", function (err)
		-- Make sure we don't go into an endless error loop
		if in_error then return end
		in_error                = true

		naughty.notify({ preset = naughty.config.presets.critical,
			title               = "Oops, an error happened!",
			text                = tostring(err) })
			in_error            = false
	end)
end
-- }}}
-- {{{ Autostart windowless processes

-- This function will run once every time Awesome is started
-- local function run_once(cmd_arr)
-- 	for _, cmd in ipairs(cmd_arr) do
-- 		awful.spawn.with_shell(string.format("pgrep -u $USER -fx '%s' > /dev/null || (%s)", cmd, cmd))
-- 	end
-- end

-- run_once({"~/scripts/autostart.sh","fcitx5 &" }) -- comma-separated entries
os.execute("~/scripts/autostart.sh")

-- {{{ Variable definitions
-- Themes define colours, icons, font and wallpapers.
beautiful.init("~/.config/awesome/themes/gtk/theme.lua")
beautiful.master_fill_policy = "expand"

-- This is used later as the default terminal and editor to run.
local terminal	 = "alacritty"
local browser	 = "google-chrome-stable"
local file_browser	 = "dolphin --platformtheme qt5ct"
local editor	 = os.getenv("EDITOR") or "nvim"
local copy_cmd_out	 = "~/scripts/copy_cmd_out.sh"
local copy_history_cmd	 = "~/scripts/copy_history_cmd.sh"
local go_dir	 = "~/scripts/go_dir.sh"
local editor_cmd = terminal .. " -e " .. editor

local modkey	 = "Mod4"
local altkey	 = "Mod1"

-- Table of layouts to cover with awful.layout.inc, order matters.
awful.layout.layouts = {
	awful.layout.suit.tile,
	awful.layout.suit.floating,
	awful.layout.suit.fair,
	awful.layout.suit.spiral,
	-- awful.layout.suit.tile.left,
	-- awful.layout.suit.tile.bottom,
	-- awful.layout.suit.tile.top,
	-- awful.layout.suit.fair.horizontal,
	-- awful.layout.suit.spiral.dwindle,
	-- awful.layout.suit.max,
	-- awful.layout.suit.max.fullscreen,
	-- awful.layout.suit.magnifier,
	-- awful.layout.suit.corner.nw,
	-- awful.layout.suit.corner.ne,
	-- awful.layout.suit.corner.sw,
	-- awful.layout.suit.corner.se,
}
-- }}}

-- {{{ Menu
myawesomemenu = {
   { "Hotkeys", function() hotkeys_popup.show_help(nil, awful.screen.focused()) end },
   { "Manual", string.format("%s -e man awesome", terminal) },
   { "Edit config", string.format("%s -e %s %s", terminal, editor, awesome.conffile) },
   { "Restart", awesome.restart },
   { "Quit", function() awesome.quit() end },
}

mymainmenu = freedesktop.menu.build {
    before = {
        { "Awesome", myawesomemenu, beautiful.awesome_icon },
        -- other triads can be put here
    },
    after = {
        { "Open terminal", terminal },
        -- other triads can be put here
    }
}

mylauncher = awful.widget.launcher({
	image = beautiful.awesome_icon,
	menu  = mymainmenu })

-- Menubar configuration
menubar.utils.terminal = terminal -- Set the terminal for applications that require it
-- }}}

-- Keyboard map indicator and switcher
mykeyboardlayout = awful.widget.keyboardlayout()

-- {{{ Wibar
-- Create a textclock widget
mytextclock = wibox.widget.textclock("<span>%Y-%m-%d %H:%M </span>")

-- Separators
-- separator = wibox.widget.textbox(' ')
-- small_spr = wibox.widget.textbox('<span font="hack 4"> </span>')

-- Create a wibox for each screen and add it
local taglist_buttons = gears.table.join(
					awful.button({ }, 1, function(t) t:view_only() end),
					awful.button({ modkey }, 1, function(t)
											  if client.focus then
												  client.focus:move_to_tag(t)
											  end
										  end),
					awful.button({ }, 3, awful.tag.viewtoggle),
					awful.button({ modkey }, 3, function(t)
											  if client.focus then
												  client.focus:toggle_tag(t)
											  end
										  end),
					awful.button({ }, 4, function(t) awful.tag.viewnext(t.screen) end),
					awful.button({ }, 5, function(t) awful.tag.viewprev(t.screen) end)
				)

local tasklist_buttons = gears.table.join(
					 awful.button({ }, 1, function (c)
											  if c == client.focus then
												  c.minimized = true
											  else
												  c:emit_signal(
													  "request::activate",
													  "tasklist",
													  {raise = true}
												  )
											  end
										  end),
					 awful.button({ }, 3, function()
											  awful.menu.client_list({ theme = { width = 250 } })
										  end),
					 awful.button({ }, 4, function ()
											  awful.client.focus.byidx(1)
										  end),
					 awful.button({ }, 5, function ()
											  awful.client.focus.byidx(-1)
										  end))


local function set_wallpaper(s)
	-- Wallpaper
	if beautiful.wallpaper then
		local wallpaper = os.getenv("HOME") .. "/.config/awesome/themes/wallpappers/wallpapper.jpg"
		-- If wallpaper is a function, call it with the screen
		if type(wallpaper) == "function" then
			wallpaper = wallpaper(s)
		end
		gears.wallpaper.maximized(wallpaper, s, true)
	end
end

local function setup_wibox(s)
	s.mywibox:setup {
		layout = wibox.layout.align.horizontal,
		{ -- Left widgets
			layout = wibox.layout.fixed.horizontal,
			mylauncher,
			s.mytaglist,
			s.mypromptbox,
		},
		s.mytasklist, -- Middle widget
		{ -- Right widgets
			layout = wibox.layout.fixed.horizontal,
			mykeyboardlayout,
			wibox.widget.systray(),
			mytextclock,
			s.mylayoutbox,

		},
	}
end
-- Re-set wallpaper when a screen's geometry changes (e.g. different resolution)
screen.connect_signal("property::geometry", set_wallpaper)

awful.screen.connect_for_each_screen(function(s)
	-- Wallpaper
	set_wallpaper(s)

	-- Each screen has its own tag table.
	awful.tag({ "1:workspace", "2:files", "3:browser", "4:notes", "5:fsearch", "6:VMs", "7:code", "8:pdf", "9:shell" }, s, awful.layout.layouts[1])

	-- Create a promptbox for each screen
	s.mypromptbox = awful.widget.prompt()
	-- Create an imagebox widget which will contain an icon indicating which layout we're using.
	-- We need one layoutbox per screen.
	s.mylayoutbox = awful.widget.layoutbox(s)
	s.mylayoutbox:buttons(gears.table.join(
						   awful.button({ }, 1, function () awful.layout.inc( 1) end),
						   awful.button({ }, 3, function () awful.layout.inc(-1) end),
						   awful.button({ }, 4, function () awful.layout.inc( 1) end),
						   awful.button({ }, 5, function () awful.layout.inc(-1) end)))
	-- Create a taglist widget
	-- s.mytaglist = awful.widget.taglist {
	-- 	screen	= s,
	-- 	filter	= awful.widget.taglist.filter.all,
	-- 	buttons = taglist_buttons
	s.mytaglist = awful.widget.taglist {
    screen  = s,
    filter  = awful.widget.taglist.filter.all,
    style   = {
        shape = gears.shape.powerline
    },
    layout   = {
        spacing = -12,
        spacing_widget = {
            color  = '#dddddd',
            shape  = gears.shape.rounded_bar,
            -- widget = wibox.widget.separator,
        },
        layout  = wibox.layout.fixed.horizontal
    },
    widget_template = {
        {
            {
                {
                    {
                        {
                            id     = 'index_role',
                            widget = wibox.widget.textbox,
                        },
                        margins = 4,
                        widget  = wibox.container.margin,
                    },
                    bg     = '#dddddd',
                    shape  = gears.shape.circle,
                    widget = wibox.container.background,
                },
                {
                    {
                        id     = 'icon_role',
                        widget = wibox.widget.imagebox,
                    },
                    margins = 2,
                    widget  = wibox.container.margin,
                },
                {
                    id     = 'text_role',
                    widget = wibox.widget.textbox,
                },
                layout = wibox.layout.fixed.horizontal,
            },
            left  = 18,
            right = 18,
            widget = wibox.container.margin
        },
        id     = 'background_role',
        widget = wibox.container.background,
        -- Add support for hover colors and an index label
        create_callback = function(self, c3, index, objects) --luacheck: no unused args
            self:get_children_by_id('index_role')[1].markup = '<b> '..index..' </b>'
            self:connect_signal('mouse::enter', function()
                if self.bg ~= '#315bef' then
                    self.backup     = self.bg
                    self.has_backup = true
                end
                self.bg = '#315bef'
            end)
            self:connect_signal('mouse::leave', function()
                if self.has_backup then self.bg = self.backup end
            end)
        end,
        update_callback = function(self, c3, index, objects) --luacheck: no unused args
            self:get_children_by_id('index_role')[1].markup = '<b> '..index..' </b>'
        end,
    },
    buttons = taglist_buttons
}-- }
	

	-- Create a tasklist widget
	-- s.mytasklist = awful.widget.tasklist {
	-- 	screen	= s,
	-- 	filter	= awful.widget.tasklist.filter.currenttags,
	-- 	buttons = tasklist_buttons
-- }

-- s.mytasklist = awful.widget.tasklist {
--     screen   = s,
--     filter   = awful.widget.tasklist.filter.currenttags,
--     buttons  = tasklist_buttons,
--     layout   = {
--         spacing_widget = {
--             {
--                 forced_width  = 5,
--                 forced_height = 24,
--                 thickness     = 1,
--                 color         = '#777777',
--                 widget        = wibox.widget.separator
--             },
--             valign = 'center',
--             halign = 'center',
--             widget = wibox.container.place,
--         },
--         spacing = 1,
--         layout  = wibox.layout.fixed.horizontal
--     },
--     -- Notice that there is *NO* wibox.wibox prefix, it is a template,
--     -- not a widget instance.
--     widget_template = {
--         {
--             wibox.widget.base.make_widget(),
--             forced_height = 5,
--             id            = 'background_role',
--             widget        = wibox.container.background,
--         },
--         {
--             {
--                 id     = 'clienticon',
--                 widget = awful.widget.clienticon,
--             },
--             margins = 5,
--             widget  = wibox.container.margin
--         },
--         nil,
--         create_callback = function(self, c, index, objects) --luacheck: no unused args
--             self:get_children_by_id('clienticon')[1].client = c
--         end,
--         layout = wibox.layout.align.vertical,
--     },
-- }
s.mytasklist = awful.widget.tasklist {
    screen   = s,
    filter   = awful.widget.tasklist.filter.currenttags,
    buttons  = tasklist_buttons,
    style    = {
        shape_border_width = 1,
        shape_border_color = '#777777',
        shape  = gears.shape.rounded_bar,
    },
    layout   = {
        spacing = 10,
        spacing_widget = {
            {
                forced_width = 5,
                shape        = gears.shape.circle,
                widget       = wibox.widget.separator
            },
            valign = 'center',
            halign = 'center',
            widget = wibox.container.place,
        },
        layout  = wibox.layout.flex.horizontal
    },
    -- Notice that there is *NO* wibox.wibox prefix, it is a template,
    -- not a widget instance.
    widget_template = {
        {
            {
                {
                    {
                        id     = 'icon_role',
                        widget = wibox.widget.imagebox,
                    },
                    margins = 2,
                    widget  = wibox.container.margin,
                },
                {
                    id     = 'text_role',
                    widget = wibox.widget.textbox,
                },
                layout = wibox.layout.fixed.horizontal,
            },
            left  = 10,
            right = 10,
            widget = wibox.container.margin
        },
        id     = 'background_role',
        widget = wibox.container.background,
    },
}

	-- Create the wibox
	s.mywibox = awful.wibar({ position = "top", screen = s })

	-- Add widgets to the wibox
	setup_wibox(s)
end)
-- }}}


-- {{{ Mouse bindings
root.buttons(gears.table.join(
	awful.button({ }, 3, function () mymainmenu:toggle() end),
	awful.button({ }, 4, awful.tag.viewnext),
	awful.button({ }, 5, awful.tag.viewprev)
))
-- }}}

-- {{{ Key bindings
globalkeys = gears.table.join( awful.key({ modkey,			 }, "/",	  hotkeys_popup.show_help,
        { description = "show help", group="awesome"}),
	awful.key({ modkey,	altkey  }, "h",   awful.tag.viewprev,
        { description = "view previous tag", group = "tag"}),

	awful.key({ modkey,	altkey  }, "l",  awful.tag.viewnext,
        { description = "view next tag", group = "tag"}),

	awful.key({ modkey,			  }, "Escape", awful.tag.history.restore,
        { description = "return previous tag", group = "tag"}),

	-- By-direction client focus
	awful.key({ modkey }, "j",
		function()
			awful.client.focus.global_bydirection("down")
			if client.focus then client.focus:raise() end
		end,
		{description = "focus last", group = "client"}),
	awful.key({ modkey }, "k",
		function()
			awful.client.focus.global_bydirection("up")
			if client.focus then client.focus:raise() end
		end,
		{description = "focus up", group = "client"}),
	awful.key({ modkey }, "h",
		function()
			awful.client.focus.global_bydirection("left")
			if client.focus then client.focus:raise() end
		end,
		{description = "focus left", group = "client"}),
	awful.key({ modkey }, "l",
		function()
			awful.client.focus.global_bydirection("right")
			if client.focus then client.focus:raise() end
		end,
		{description = "focus right", group = "client"}),
	-- Menu
	awful.key({ modkey,			  }, "w", function () mymainmenu:show() end,
			  {description = "show main menu", group = "awesome"}),

	awful.key({ modkey, "Control" }, "n",
			  function ()
				  local c = awful.client.restore()
				  -- Focus restored client
				  if c then
					c:emit_signal(
						"request::activate", "key.unminimize", {raise = true}
					)
				  end
			  end,
			  {description = "restore minimized", group = "client"}),

	awful.key({ modkey, "Shift"   }, "j", function () awful.client.swap.byidx(	1)	  end,
			  {description = "swap with next client by index", group = "client"}),
	awful.key({ modkey, "Shift"   }, "j", function () awful.client.swap.byidx(	1)	  end,
			  {description = "swap with next client by index", group = "client"}),

	awful.key({ modkey, "Shift"   }, "k", function () awful.client.swap.byidx( -1)	  end,
			  {description = "swap with previous client by index", group = "client"}),

	awful.key({ modkey}, ",", function () awful.screen.focus_relative( 1) end,
			  {description = "focus the next screen", group = "screen"}),

	awful.key({ modkey}, ".", function () awful.screen.focus_relative(-1) end,
			  {description = "focus the previous screen", group = "screen"}),

	awful.key({ modkey,			  }, "u", awful.client.urgent.jumpto,
			  {description = "jump to urgent client", group = "client"}),

	awful.key({ modkey,			  }, "Tab",
		function ()
			if cycle_prev then
				awful.client.focus.history.previous()
			else
				awful.client.focus.byidx(-1)
			end
			if client.focus then
				client.focus:raise()
			end
		end,
		{description = "go back", group = "client"}),

	-- Show/hide wibox
	awful.key({ modkey }, "b", function ()
			for s in screen do
				s.mywibox.visible = not s.mywibox.visible
				if s.mybottomwibox then
					s.mybottomwibox.visible = not s.mybottomwibox.visible
				end
			end
		end,
		{description = "toggle wibox", group = "awesome"}),

	-- Standard program
	awful.key({ modkey,			  }, "Return", function () awful.spawn(terminal) end,
			  {description = "open a terminal", group = "launcher"}),
	awful.key({ modkey, "Control" }, "r", awesome.restart,
			  {description = "reload awesome", group = "awesome"}),
	awful.key({ modkey, "Ctrl"   }, "q", awesome.quit,
			  {description = "quit awesome", group = "awesome"}),

	-- switch layout
	-- awful.layout.suit.tile,
	-- awful.layout.suit.floating,
	-- awful.layout.suit.fair,
	-- awful.layout.suit.spiral,
	awful.key({ modkey, "Shift"   }, "t", function () awful.layout.set(awful.layout.suit.tile)	  end,
			  {description = "set max layout", group = "layout"}),

	awful.key({ modkey, "Shift"   }, "f", function () awful.layout.set(awful.layout.suit.float)	  end,
			  {description = "set max layout", group = "layout"}),

	awful.key({ modkey, "Shift"   }, "g", function () awful.layout.set(awful.layout.suit.fair)	  end,
			  {description = "set max layout", group = "layout"}),

	awful.key({ modkey, "Shift"   }, "m", function () awful.layout.set(awful.layout.suit.max)	  end,
			  {description = "set max layout", group = "layout"}),



	awful.key({ modkey }, "Right",		function () awful.tag.incmwfact( 0.05)			end,
			  {description = "increase master width factor", group = "layout"}),
	awful.key({ modkey }, "Left",		function () awful.tag.incmwfact(-0.05)			end,
			  {description = "decrease master width factor", group = "layout"}),
	awful.key({ modkey, "Shift"   }, "h",	  function () awful.tag.incnmaster( 1, nil, true) end,
			  {description = "increase the number of master clients", group = "layout"}),
	awful.key({ modkey, "Shift"   }, "l",	  function () awful.tag.incnmaster(-1, nil, true) end,
			  {description = "decrease the number of master clients", group = "layout"}),
	awful.key({ modkey, "Control" }, "h",	  function () awful.tag.incncol( 1, nil, true)	  end,
			  {description = "increase the number of columns", group = "layout"}),
	awful.key({ modkey, "Control" }, "l",	  function () awful.tag.incncol(-1, nil, true)	  end,
			  {description = "decrease the number of columns", group = "layout"}),


	awful.key({ modkey,			  }, "space", function () awful.layout.inc( 1)				  end,
			  {description = "select next", group = "layout"}),

	awful.key({ modkey, "Shift"   }, "space", function () awful.layout.inc(-1)				  end,
			  {description = "select previous", group = "layout"}),

	awful.key({ modkey }, "Up", function () brightness.increase_brightness()
		awful.screen.connect_for_each_screen(function(s)
			setup_wibox(s)
		end)
	end,
			  {description = "+10%", group = "hotkeys"}),

	awful.key({ modkey }, "Down", function () brightness.decrease_brightness()
		awful.screen.connect_for_each_screen(function(s)
			setup_wibox(s)
		end)
	end,
			  {description = "-10%", group = "hotkeys"}),

	-- ALSA volume control
	awful.key({ altkey }, "Up",
		function ()
			volume.increase_volume()
			awful.screen.connect_for_each_screen(function(s)
				setup_wibox(s)
			end)
			-- beautiful.volume.update()
		end,
		{description = "volume up", group = "hotkeys"}),
	awful.key({ altkey }, "Down",
		function ()
			-- os.execute(string.format("amixer -q set %s 1%%-", beautiful.volume.channel))
			volume.decrease_volume()
			awful.screen.connect_for_each_screen(function(s)
				setup_wibox(s)
			end)
			-- beautiful.volume.update()
		end,
		{description = "volume down", group = "hotkeys"}),
	awful.key({ altkey }, "m",
		function ()
			os.execute(string.format("amixer -q set %s toggle", beautiful.volume.togglechannel or beautiful.volume.channel))
			beautiful.volume.update()
		end,
		{description = "toggle mute", group = "hotkeys"}),
	awful.key({ altkey, "Control" }, "m",
		function ()
			os.execute(string.format("amixer -q set %s 100%%", beautiful.volume.channel))
			beautiful.volume.update()
		end,
		{description = "volume 100%", group = "hotkeys"}),
	awful.key({ altkey, "Control" }, "0",
		function ()
			os.execute(string.format("amixer -q set %s 0%%", beautiful.volume.channel))
			beautiful.volume.update()
		end,
		{description = "volume 0%", group = "hotkeys"}),

	-- MPD control
	awful.key({ altkey, "Control" }, "Up",
		function ()
			os.execute("mpc toggle")
			beautiful.mpd.update()
		end,
		{description = "mpc toggle", group = "widgets"}),
	awful.key({ altkey, "Control" }, "Down",
		function ()
			os.execute("mpc stop")
			beautiful.mpd.update()
		end,
		{description = "mpc stop", group = "widgets"}),
	awful.key({ altkey, "Control" }, "Left",
		function ()
			os.execute("mpc prev")
			beautiful.mpd.update()
		end,
		{description = "mpc prev", group = "widgets"}),
	awful.key({ altkey, "Control" }, "Right",
		function ()
			os.execute("mpc next")
			beautiful.mpd.update()
		end,
		{description = "mpc next", group = "widgets"}),
	awful.key({ altkey }, "0",
		function ()
			local common = { text = "MPD widget ", position = "top_middle", timeout = 2 }
			if beautiful.mpd.timer.started then
				beautiful.mpd.timer:stop()
				common.text = common.text .. lain.util.markup.bold("OFF")
			else
				beautiful.mpd.timer:start()
				common.text = common.text .. lain.util.markup.bold("ON")
			end
			naughty.notify(common)
		end,
		{description = "mpc on/off", group = "widgets"}),

	-- User programs
	awful.key({ modkey }, "c", function () awful.spawn(browser) end, {description = "run browser", group = "launcher"}),
	awful.key({ modkey }, "Print", function () awful.spawn("flameshot gui") end, {description = "run flameshot", group = "launcher"}),
	awful.key({ modkey }, "e", function () awful.spawn(file_browser) end, {description = "run file browser", group = "launcher"}),
	-- Default
	--[[ dmenu
	awful.key({ modkey }, "x", function ()
			os.execute(string.format("dmenu_run -i -fn 'Monospace' -nb '%s' -nf '%s' -sb '%s' -sf '%s'",
			beautiful.bg_normal, beautiful.fg_normal, beautiful.bg_focus, beautiful.fg_focus))
		end,
		{description = "show dmenu", group = "launcher"})
	--]]
	-- alternatively use rofi, a dmenu-like application with more features
	-- check https://github.com/DaveDavenport/rofi for more details

	-- Rofi
	awful.key({ altkey }, " ", function ()
			os.execute(string.format("rofi -show drun -theme gruvbox-light-soft.rasi"))
		end,
		{description = "show rofi", group = "launcher"}),
	awful.key({ modkey,altkey }, "o", function ()
			os.execute(copy_cmd_out)
		end,
		{description = "copy command output", group = "launcher"}),
	awful.key({ modkey,altkey }, "c", function ()
			os.execute(copy_history_cmd)
		end,
		{description = "copy history command", group = "launcher"}),
	awful.key({ modkey,altkey }, "d", function ()
			os.execute(go_dir)
		end,
		{description = "go to custom dir", group = "launcher"})
	)

clientkeys = gears.table.join(
	awful.key({ modkey,   }, "f",
		function (c)
			c.fullscreen = not c.fullscreen
			c:raise()
		end,
		{description = "toggle fullscreen", group = "client"}),
        -- view all tag
	awful.key({ modkey }, "space",  awful.client.floating.toggle						,
			  {description = "view all tag", group = "client"}),
	awful.key({ modkey, "Shift" }, "o", 
                function()
                        local screen = awful.screen.focused()
                        awful.tag.viewmore(screen.tags)
                    end,
			  {description = "toggle floating", group = "client"}),

	awful.key({ modkey, "Control" }, "Return", function (c) c:swap(awful.client.getmaster()) end,
			  {description = "move to master", group = "client"}),

	awful.key({ modkey,			  }, "o",	   function (c) c:move_to_screen()				 end,
			  {description = "move to screen", group = "client"}),

	awful.key({ modkey,			  }, "t",	   function (c) c.ontop = not c.ontop			 end,
			  {description = "toggle keep on top", group = "client"}),

	awful.key({ modkey,			  }, "n",
		function (c)
			-- The client currently has the input focus, so it cannot be
			-- minimized, since minimized clients can't have the focus.
			c.minimized = true
		end ,
			{description = "minimize", group = "client"}),
	

	-- client size control
	awful.key({ modkey	}, "q",		 function (c) c:kill()						   end,
			  {description = "close", group = "client"}),

	awful.key({ modkey,			  }, "m",
		function (c)
			c.maximized = not c.maximized
			c:raise()
		end ,
		{description = "(un)maximize", group = "client"}),

	awful.key({ modkey, "Control" }, "m",
		function (c)
			c.maximized_vertical = not c.maximized_vertical
			c:raise()
		end ,
		{description = "(un)maximize vertically", group = "client"}),

	awful.key({ modkey, "Shift"   }, "m",
		function (c)
			c.maximized_horizontal = not c.maximized_horizontal
			c:raise()
		end ,
		{description = "(un)maximize horizontally", group = "client"})
)

-- Bind all key numbers to tags.
-- Be careful: we use keycodes to make it work on any keyboard layout.
-- This should map on the top row of your keyboard, usually 1 to 9.
for i = 1, 9 do
	globalkeys = gears.table.join(globalkeys,
		-- View tag only.
		awful.key({ modkey }, "#" .. i + 9,
				  function ()
						local screen = awful.screen.focused()
						local tag = screen.tags[i]
						if tag then
						   tag:view_only()
						end
				  end,
				  {description = "view tag #"..i, group = "tag"}),
		-- Toggle tag display.
		awful.key({ modkey, "Control" }, "#" .. i + 9,
				  function ()
					  local screen = awful.screen.focused()
					  local tag = screen.tags[i]
					  if tag then
						 awful.tag.viewtoggle(tag)
					  end
				  end,
				  {description = "toggle tag #" .. i, group = "tag"}),
		-- Move client to tag and view on tag.
		awful.key({ modkey, "Shift" }, "#" .. i + 9,
				  function ()
					  if client.focus then
						  local tag = client.focus.screen.tags[i]
						  if tag then
							  client.focus:move_to_tag(tag)
                              local screen = awful.screen.focused()
                              local tag2 = screen.tags[i]
                              tag:view_only()
						  end
					 end
				  end,
				  {description = "move focused client to tag #"..i, group = "tag"}),
		-- Toggle tag on focused client.
		awful.key({ modkey, "Control", "Shift" }, "#" .. i + 9,
				  function ()
					  if client.focus then
						  local tag = client.focus.screen.tags[i]
						  if tag then
							  client.focus:toggle_tag(tag)
						  end
					  end
				  end,
				  {description = "toggle focused client on tag #" .. i, group = "tag"})
	)
end

clientbuttons = gears.table.join(
	awful.button({ }, 1, function (c)
		c:emit_signal("request::activate", "mouse_click", {raise = true})
	end),
	awful.button({ modkey }, 1, function (c)
		c:emit_signal("request::activate", "mouse_click", {raise = true})
		awful.mouse.client.move(c)
	end),
	awful.button({ modkey }, 3, function (c)
		c:emit_signal("request::activate", "mouse_click", {raise = true})
		awful.mouse.client.resize(c)
	end)
)

-- Set keys
root.keys(globalkeys)
-- }}}

-- {{{ Rules
-- Rules to apply to new clients (through the "manage" signal).
awful.rules.rules = {
	-- All clients will match this rule.
	{ rule = { },
	  properties = { border_width = beautiful.border_width,
					 border_color = beautiful.border_normal,
					 focus = awful.client.focus.filter,
					 raise = true,
					 keys = clientkeys,
					 buttons = clientbuttons,
					 screen = awful.screen.preferred,
					 placement = awful.placement.no_overlap+awful.placement.no_offscreen,
					 size_hints_honor = false
	 }
	},

	-- Floating clients.
	{ rule_any = {
		instance = {
		  "DTA",  -- Firefox addon DownThemAll.
		  "copyq",	-- Includes session name in class.
		  "pinentry",
		},
		class = {
		  "Arandr",
		  "Blueman-manager",
		  "Gpick",
		  "Kruler",
		  "MessageWin",  -- kalarm.
		  "Sxiv",
		  "Tor Browser", -- Needs a fixed window size to avoid fingerprinting by screen size.  "Wpa_gui",
		  "VirtualBox Machine",
		  "veromix",
		  "xtightvncviewer"},

		-- Note that the name property shown in xprop might be set slightly after creation of the client
		-- and the name shown there might not match defined rules here.
		name = {
		  "Event Tester",  -- xev.
		},
		role = {
		  "AlarmWindow",  -- Thunderbird's calendar.
		  "ConfigManager",	-- Thunderbird's about:config.
		  "pop-up",		  -- e.g. Google Chrome's (detached) Developer Tools.
		}
	  }, properties = { floating = true }},

	-- 取消标题栏
	{ rule_any = {type = { "normal", "dialog" }
	  }, properties = { titlebars_enabled = false }
	},
	-- 测试规则
	{ rule_any = {class = { "Plank","fcitx" }
	  }, properties = { border_width = 0 }
	},
	{rule_any = { class={"VirtualBox Manager", "VirtualBox Manager"},properties = {floating = true}}},
	{ rule_any = { class = {"firefox","Google-chrome"} },
		properties = {tag = "3:browser" },
		callback = function()
			toogle_to_tag(3)
		end
	},

	{ rule_any = { class = {"dolphin","thunar"} },
		 properties = {tag = "2:files" },
		callback = function()
			toogle_to_tag(2)
		end
	 },
	{ rule = { class = "Fsearch" },
		 properties = {tag = "5:fsearch" },
		callback = function()
			toogle_to_tag(5)
		end
	 },
	{ rule_any = { class = {"VNote","Typora"} },
		 properties = {tag = "4:notes" },
		callback = function()
			toogle_to_tag(4)
		end
	},
	{ rule = { class = "Vmware" },
		properties = {tag = "6:VMs" },
		callback = function()
			toogle_to_tag(6)
		end
	 },
	{ rule = { class = "nvim-qt" },
		properties = {tag = "7:code" },
		callback = function()
			toogle_to_tag(7)
		end
	 },
	{ rule = { class = "okular" },
		properties = {tag = "8:pdf" },
		callback = function()
			toogle_to_tag(8)
		end
	 },
}
-- }}}

-- {{{ Signals
-- Signal function to execute when a new client appears.
client.connect_signal("manage", function (c)
	-- Set the windows at the slave,
	-- i.e. put it at the end of others instead of setting it master.
	-- if not awesome.startup then awful.client.setslave(c) end

	if awesome.startup
	  and not c.size_hints.user_position
	  and not c.size_hints.program_position then
		-- Prevent clients from being unreachable after screen count changes.
		awful.placement.no_offscreen(c)
	end
end)

-- Add a titlebar if titlebars_enabled is set to true in the rules.
client.connect_signal("request::titlebars", function(c)
	-- buttons for the titlebar
	local buttons = gears.table.join(
		awful.button({ }, 1, function()
			c:emit_signal("request::activate", "titlebar", {raise = true})
			awful.mouse.client.move(c)
		end),
		awful.button({ }, 3, function()
			c:emit_signal("request::activate", "titlebar", {raise = true})
			awful.mouse.client.resize(c)
		end)
	)

	awful.titlebar(c) : setup {
		{ -- Left
			awful.titlebar.widget.iconwidget(c),
			buttons = buttons,
			layout	= wibox.layout.fixed.horizontal
		},
		{ -- Middle
			{ -- Title
				align  = "center",
				widget = awful.titlebar.widget.titlewidget(c)
			},
			buttons = buttons,
			layout	= wibox.layout.flex.horizontal
		},
		{ -- Right
			awful.titlebar.widget.floatingbutton (c),
			awful.titlebar.widget.maximizedbutton(c),
			awful.titlebar.widget.stickybutton	 (c),
			awful.titlebar.widget.ontopbutton	 (c),
			awful.titlebar.widget.closebutton	 (c),
			layout = wibox.layout.fixed.horizontal()
		},
		layout = wibox.layout.align.horizontal
	}
end)

-- Enable sloppy focus, so that focus follows mouse.
-- 关闭焦点跟随鼠标移动
-- client.connect_signal("mouse::enter", function(c)
-- 	c:emit_signal("request::activate", "mouse_enter", {raise = false})
-- end)

client.connect_signal("focus", function(c) c.border_color = beautiful.border_focus end)
client.connect_signal("unfocus", function(c) c.border_color = beautiful.border_normal end)
-- }}}

